package com.beyondsoft.sabg.edu.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @Author Mo cr
 * @Date 2025/2/17
 */
public class RequestUtils {
    /**
     * 发送西电数据中台请求
     * @param url
     * @param param
     * @return
     */
    public static JSONObject sendPostRequest(String url, JSONObject param) {
        //定义接收数据
        JSONObject result = new JSONObject();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        //请求参数转JOSN字符串
        StringEntity entity = new StringEntity(param.toString(), "UTF-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        try {
            HttpResponse response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
            result.put("error", "连接错误！");
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                result.put("error", "连接错误！");
            }
        }
        return result;
    }

    public static String acquireAccessToken() {
        //定义发送数据
        JSONObject param = new JSONObject();
        param.put("key","20220407160915119222101624832005417");
        param.put("secret", "dee622a78477026aea58d2102152876ec72fa0ab");
        JSONObject res = sendPostRequest("TOKEN_ACQUIRE_URL", param);
        if (res == null || res.getInteger("code") != 10000) {
            return "";
        }
        String token = res.getJSONObject("result").getString("access_token");
        return token;
    }
}
